package com.trolls.client;

import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;

public class CompositeFormEditTroll extends Composite {
	private Troll trollEdit;
	private VerticalPanel vPanelPrincipal;
	private VerticalPanel vPanelCaracteristiques;
	private VerticalPanel vPanelCompetences;
	private TextArea description;
	private int maxPtsCarac = 50;
	private int maxPtsComp = 20;
	private HTML serveurInfo;
	public CompositeFormEditTroll(final Troll troll) {
		trollEdit = troll;
		serveurInfo = new HTML();
		this.vPanelCaracteristiques = new VerticalPanel();
		this.vPanelCompetences = new VerticalPanel();
		vPanelPrincipal = new VerticalPanel();
		// AFFICHAGE de la race
		HTML labelRace = new HTML("Race");
		labelRace.setStyleName("titre3");
		HorizontalPanel hPanelRace = new HorizontalPanel();

		PushButton buttonRace = new PushButton("Choisir");
		buttonRace.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				trollEdit = SauveModifs(trollEdit);
				LaTerreDesTrolls.get().ChoiceTrollRace(trollEdit);
			}

		});
		TextBox tbRace = new TextBox();
		tbRace.setName("race");
		tbRace.setValue(trollEdit.getRace().getName());
		tbRace.setEnabled(false);
		hPanelRace.add(labelRace);
		hPanelRace.add(tbRace);
		hPanelRace.add(buttonRace);

		vPanelPrincipal.add(hPanelRace);

		// -----------------------  AFFICHAGE des Caractéritiques
		HTML labelCarac = new HTML("Caractéristiques");
		labelCarac.setStyleName("titre3");
		Vector<String> caracList = new Vector<String>();
		caracList.add("Attaque");
		caracList.add("Dégats");
		caracList.add("Esquive");
		caracList.add("régénération");
		caracList.add("points de vie");

		vPanelPrincipal.add(labelCarac);
		afficheCompetences(caracList, vPanelCaracteristiques);// Affiche les
																// inputs
		vPanelPrincipal.add(vPanelCaracteristiques);

		// ----------------------- AFFICHAGE des Compétences
		HTML labelComp = new HTML("Compétences");
		labelComp.setStyleName("titre3");
		Vector<String> compList = new Vector<String>();
		compList.add(trollEdit.getRace().getCompetenceSpeciale());
		compList.add(trollEdit.getRace().getCompetenceSpecialeSecondaire());

		vPanelPrincipal.add(labelComp);
		afficheCompetences(compList, vPanelCompetences);
		vPanelPrincipal.add(vPanelCompetences);
		
		// -----------------------  UPLOAD d'images:
		HorizontalPanel hPanelUpload = new HorizontalPanel();
		final FormPanel uploadForm = new FormPanel();
		final FileUpload upload = new FileUpload();

		uploadForm.setAction(GWT.getModuleBaseURL() + "UploadImage"); 

		// Pour ajouter un FileUpload widget, nous devons ajouter au formulaire 
		// une méthode d'envoie POST, et un encodage multipart MIME. 
		 uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART); 
		 uploadForm.setMethod(FormPanel.METHOD_POST); 
		
		// Ajout du panel au formulaire 

		 
		 // Propriétés du FileUpload widget. 
		  upload.setName("uploadFormElement");
		  HTML labelUpload = new HTML("Image");
		  labelUpload.setStyleName("titre3");
		  hPanelUpload.add(labelUpload);
		  hPanelUpload.add(upload); 
		  Button uploadSubmitButton = new Button("Envoyer"); 
	
		  hPanelUpload.add(uploadSubmitButton); 
		  uploadSubmitButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				uploadForm.submit();
				
			}
		});
		  uploadForm.add(hPanelUpload); 
		  uploadForm.addSubmitHandler(new SubmitHandler() {
			
			@Override
			public void onSubmit(SubmitEvent event) {
					System.out.println("upload");
					System.out.println(uploadForm.getWidget());				

			}
		} );

		  uploadForm.addSubmitCompleteHandler(new SubmitCompleteHandler() {
			
			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
				// TODO Auto-generated method stub
				
				if(!(event.getResults().indexOf("[")<0)){
					String nomImg =event.getResults().substring(event.getResults().indexOf("[")+1, event.getResults().indexOf("]"));

					trollEdit =SauveModifs(trollEdit);
					trollEdit.setImage(nomImg);
					LaTerreDesTrolls.get().getContent().showTroll(trollEdit);
					serveurInfo.setHTML("Image Enregistrée :"+trollEdit.getImagePath());
				}else{
					serveurInfo.setHTML("Le format du fichier est incorrect");					
				}
			}
		});

		  vPanelPrincipal.add(uploadForm) ;
		// -----------------------  AFFICHAGE ds boutons Enregistrer & Supprimer
		HorizontalPanel hPanelEnregistrer = new HorizontalPanel();
		Button buttonEnregistrer = new Button("Enregistrer",
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						SauveModifs(trollEdit).save();
					}
				});
		Button buttonSupprimer = new Button("Supprimer",
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						SauveModifs(trollEdit).delete();
					}
				});
		if(troll.getId()==0){buttonSupprimer.setEnabled(false);}
		hPanelEnregistrer.add(buttonEnregistrer);
		hPanelEnregistrer.add(buttonSupprimer);
		hPanelEnregistrer.add(serveurInfo);
		vPanelPrincipal.add(hPanelEnregistrer);
		TabPanel tPanel = new TabPanel();
		description = new TextArea();
		description.setWidth("98%");
		tPanel.add(vPanelPrincipal, "Caracteristiques");
		tPanel.add(description, "Histoire");
		tPanel.selectTab(0);
		this.initWidget(tPanel);

	}

	public void afficheCompetences(Vector<String> competences, VerticalPanel vP) {
		HorizontalPanel hpanelPtsRestants = new HorizontalPanel();
		Label lbPtsRestants = new Label("Points restants: ");
		hpanelPtsRestants.add(lbPtsRestants);
		final TextBox tbPtsRestants = new TextBox();
		lbPtsRestants.setStyleName("labelPtsRestants");
		hpanelPtsRestants.add(tbPtsRestants);
		tbPtsRestants.setSize("20px", "12px");
		tbPtsRestants.setEnabled(false);
		for (String competence : competences) {
			HorizontalPanel h = new HorizontalPanel();
			final TextBox tb = new TextBox();
			Label lb = new Label(competence);
			lb.setStyleName("labelCompetence");

			PushButton buttonMore = new PushButton(new Image(
					GWT.getHostPageBaseURL() + "images/util/add.png"));
			buttonMore.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					more(tb, tbPtsRestants);
				}
			});
			PushButton buttonLess = new PushButton(new Image(
					GWT.getHostPageBaseURL() + "images/util/less.png"));
			buttonLess.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					less(tb, tbPtsRestants);
				}
			});
			tb.setName(competence);
			tb.setSize("20px", "16px");
			tb.setEnabled(false);
			h.add(lb);
			h.add(buttonLess);
			h.add(tb);
			h.add(buttonMore);
			vP.add(h);

		}

		vP.add(hpanelPtsRestants);
	}

	public void showTroll(Troll troll) {
		int ptsTotal = 0;
		trollEdit = troll;
		getTextBox(vPanelPrincipal, 0, 1).setValue(
				troll.getRace().getName());
		ptsTotal = troll.getPtsAttaque() + troll.getPtsDegat()
				+ troll.getPtsEsquive() + troll.getPtsRegeneration()
				+ troll.getPtsPv();
		getTextBox(vPanelCaracteristiques, 0, 2).setValue(
				String.valueOf(troll.getPtsAttaque()));
		getTextBox(vPanelCaracteristiques, 1, 2).setValue(
				String.valueOf(troll.getPtsDegat()));
		getTextBox(vPanelCaracteristiques, 2, 2).setValue(
				String.valueOf(troll.getPtsEsquive()));
		getTextBox(vPanelCaracteristiques, 3, 2).setValue(
				String.valueOf(troll.getPtsRegeneration()));
		getTextBox(vPanelCaracteristiques, 4, 2).setValue(
				String.valueOf(troll.getPtsPv()));

		getTextBox(vPanelCaracteristiques, 5, 1).setValue(
				String.valueOf(maxPtsCarac - ptsTotal));
		ptsTotal = 0;
		ptsTotal = troll.getPtsCompetenceSpecial()
				+ troll.getPtsCompetenceSpecialSecondaire();
		getTextBox(vPanelCompetences, 0, 2).setValue(
				String.valueOf(troll.getPtsCompetenceSpecial()));
		getTextBox(vPanelCompetences, 1, 2).setValue(
				String.valueOf(troll.getPtsCompetenceSpecialSecondaire()));
		getTextBox(vPanelCompetences, 2, 1).setValue(
				String.valueOf(maxPtsComp - ptsTotal));
		description.setText(troll.getDescription());
		SetInfoServeur("");
	}

	public int countPtsTotal(VerticalPanel vP) {
		int pts = 0;
		for (int i = 0; i < vP.getWidgetCount() - 1; i++) {
			pts = pts
					+ Integer.parseInt(((TextBox) ((HorizontalPanel) vP
							.getWidget(i)).getWidget(2)).getValue());
		}
		return pts;
	}

	public void more(TextBox tb, TextBox tbPtsRestants) {
		int val = Integer.parseInt(tb.getValue());
		int nbPtsRestant = Integer.parseInt(tbPtsRestants.getValue());
		if (nbPtsRestant > 0) {
			tbPtsRestants.setValue(String.valueOf(nbPtsRestant - 1));
			tb.setValue(String.valueOf(val + 1));
		}
	}

	public void less(TextBox tb, TextBox tbPtsRestants) {
		int val = Integer.parseInt(tb.getValue());
		int nbPtsRestant = Integer.parseInt(tbPtsRestants.getValue());
		if (nbPtsRestant < 50 && Integer.parseInt(tb.getValue())>0) {
			tbPtsRestants.setValue(String.valueOf(nbPtsRestant + 1));
			tb.setValue(String.valueOf(val - 1));
		}
	}

	private Troll SauveModifs(Troll troll) {
		troll.setPtsAttaque(Integer.parseInt(getTextBox(vPanelCaracteristiques,
				0, 2).getValue()));
		troll.setPtsDegat(Integer.parseInt(getTextBox(vPanelCaracteristiques,
				1, 2).getValue()));
		troll.setPtsEsquive(Integer.parseInt(getTextBox(vPanelCaracteristiques,
				2, 2).getValue()));
		troll.setPtsRegeneration(Integer.parseInt(getTextBox(
				vPanelCaracteristiques, 3, 2).getValue()));
		troll.setPtsPv(Integer
				.parseInt(getTextBox(vPanelCaracteristiques, 4, 2).getValue()));
		troll.setPtsCompetenceSpecial(Integer.parseInt(getTextBox(
				vPanelCompetences, 0, 2).getValue()));
		troll.setPtsCompetenceSpecialSecondaire(Integer.parseInt(getTextBox(
				vPanelCompetences, 1, 2).getValue()));
		troll.setName(LaTerreDesTrolls.get().getContent().getNewName());
		troll.setDescription(description.getText());
		return troll;
		// TODO Auto-generated method stub

	}

	public TextBox getTextBox(VerticalPanel panel, int numLigne, int numWidget) {
		return ((TextBox) (((HorizontalPanel) panel.getWidget(numLigne))
				.getWidget(numWidget)));
	}
	public void SetInfoServeur(String str){
		serveurInfo.setHTML(str);
	}

	public void SetServeurInfo(String str) {
		// TODO Auto-generated method stub
		serveurInfo.setHTML(str);
	}

	public Item getItemEnCour() {
		// TODO Auto-generated method stub
		return trollEdit;
	}
}
